package com.tan.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tan.exception.BusinessException;
import com.tan.pojo.AliOss;
import com.tan.pojo.User;
import com.tan.pojo.vo.UserInnerDepartmentVO;
import com.tan.response.Result;
import com.tan.response.ResultCode;
import com.tan.service.impl.UserServiceImpl;
import com.tan.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author tanRuYi
 * @since 2021-08-25
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(tags = "用户模块")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    RedisUtil redisUtil;

    @ApiOperation("查询全部的用户")
    @PostMapping("/getAll")
    public Result getAll(
            @RequestParam("currentPage") Integer currentPage,
            @RequestParam("pageSize") Integer pageSize,
            UserInnerDepartmentVO user
    ) {

        final Page<UserInnerDepartmentVO> page = new Page<>(currentPage, pageSize);

        final Page<UserInnerDepartmentVO> userByUserByPage = this.userService.getUserByUserByPage(user, page);

        return Result.ok().data("data", userByUserByPage);
    }

    @ApiOperation("根据id删除用户")
    @PostMapping("/deleteById")
    public Result deleteUserById(Integer userId) {

        if (userId == null || userId < 0) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);
        }

        if (userService.removeById(userId)) {
            return Result.ok();
        } else {
            return Result.error(ResultCode.PARAM_NOT_VALID);
        }
    }

    @ApiOperation(("添加用户"))
    @PostMapping("/add")
    public Result addUser(User user) {

        if (user == null) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);
        }

        if (userService.save(user)) {
            return Result.ok();
        } else {
            return Result.error(ResultCode.PARAM_NOT_VALID);
        }
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public Result updateUser(User user){

        if (user == null) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);
        }

        if (userService.updateById(user)) {
            return Result.ok();
        } else {
            return Result.error(ResultCode.PARAM_NOT_VALID);
        }
    }

    @ApiOperation("上传头像信息")
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file){

        // 判断是否为null
        if (file.isEmpty()){
            return Result.error(ResultCode.FILE_NULL);
        }

        // 得到上传文件名称
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        // 使用上传文件名称 判断文件类型
        if ("txt".contains(fileType)){
            return Result.error(ResultCode.FILE_TYPE_EXCEPTION);
        }

        System.out.println(fileType);
        String path = "E:\\tanRuYi\\Y2\\IntegrationProject\\code-parent\\logs\\";
        // 创建一个路径对象
        Path filePath = Paths.get(path + originalFilename);

        try {
            // 根据对象 得到byte字节数组
            byte[] fileBytes = file.getBytes();

            // 根据路径对象 将字节输出进行输出
            Files.write(filePath, fileBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.ok();
    }

    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, UserInnerDepartmentVO userVO) throws IOException {
        QueryWrapper<User> wrapper = getWrapper(userVO);
        wrapper.select("id", "username", "nickname", "email", "avatar", "phone_number", "create_time", "modified_time", "sex", "birth", "department_id");
        List<User> users = userService.list(wrapper);
        userService.exportUserExcel(response,users);
    }

    /**
     * 封装查询条件
     */
    private QueryWrapper<User> getWrapper(UserInnerDepartmentVO userVO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userVO != null) {
            if (!StringUtils.isEmpty(userVO.getDepartmentId())) {
                queryWrapper.eq("department_id", userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())) {
                queryWrapper.eq("username", userVO.getUsername());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())) {
                queryWrapper.eq("email", userVO.getEmail());
            }
            if (!StringUtils.isEmpty(userVO.getSex())) {
                queryWrapper.eq("sex", userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())) {
                queryWrapper.eq("nickname", userVO.getNickname());
            }
        }
        return queryWrapper;
    }

    @GetMapping("getImg")
    public void getImg(HttpServletResponse response) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());

        redisUtil.set("imgCode", lineCaptcha.getCode(), 1000 * 60 * 10);
    }

    @ApiOperation(value = "登录",notes = "传入用户名和密码")
    @PostMapping("/login")
    public Result login(@RequestParam(value = "username",required = true) String username,
                        @RequestParam(value = "password",required = true) String password,
                        @RequestParam(value = "verifyCode", required = true) String verifyCode
    ){

        if (redisUtil.get("imgCode") != null && verifyCode.equals(redisUtil.get("imgCode"))){

            String token = userService.login(username,password);
            return Result.ok().data("token",token);
        }

        return Result.error(ResultCode.LOGIN_VERIFY_CODE_EXCEPTION);

    }
}

